﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ModularFixture.CApMFMappingReportDataManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Resources;
using System.Windows.Forms;
using Tecnomatix.Engineering;
using Tecnomatix.Planning;


namespace DnProcessSimulateCommands.ModularFixture;

internal class CApMFMappingReportDataManager
{
  private CApMFExcelManager m_excelManager;
  private List<TxCompoundResource> m_fixtures;
  private List<TxMfgFeature> m_usedPlps;
  private List<TxMfgFeature> m_notUsedPlps;
  private CApMFPlpUsageManager m_plpUsageManager;
  private bool m_canGetPlpUsage;

  public CApMFMappingReportDataManager()
  {
    this.m_excelManager = new CApMFExcelManager();
    this.m_fixtures = new List<TxCompoundResource>();
    this.m_usedPlps = new List<TxMfgFeature>();
    this.m_notUsedPlps = new List<TxMfgFeature>();
    this.m_plpUsageManager = new CApMFPlpUsageManager();
    this.m_canGetPlpUsage = true;
  }

  public void ClearData()
  {
    this.m_fixtures.Clear();
    this.m_usedPlps.Clear();
    this.m_notUsedPlps.Clear();
  }

  public bool ProcessData(ITxPlanningObject root)
  {
    this.m_plpUsageManager.ClearData();
    this.m_canGetPlpUsage = true;
    switch (this.m_plpUsageManager.InitToolTypes())
    {
      case CApMFMappingReportUtils.EDataStatus.dataValid:
        if (!this.m_plpUsageManager.CachePlpUsageData())
        {
          this.ShowMessage("DATA_FAIL_TOOL_TYPE_PLP_USAGE", "WARNING_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
          this.m_canGetPlpUsage = false;
          goto label_6;
        }
        goto label_6;
      case CApMFMappingReportUtils.EDataStatus.dataNotLoaded:
        this.ShowMessage("XML_MISSING_TOOL_TYPE_PLP_USAGE", "WARNING_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        break;
      default:
        this.ShowMessage("XML_INCORRECT_TOOL_TYPE_PLP_USAGE", "WARNING_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        break;
    }
    this.m_canGetPlpUsage = false;
label_6:
    bool flag = this.CollectData(root);
    if (!flag)
    {
      this.ShowMessage("REPORT_FAILED", "ERROR_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    else
    {
      List<CApMFExportData> fixtures = this.PrepareFixturesExportData();
      List<CApMFExportData> plps = this.PreparePlpsExportData();
      if (fixtures != null && plps != null)
      {
        if (fixtures.Count == this.m_fixtures.Count && plps.Count == this.m_notUsedPlps.Count)
        {
          flag = this.ExportCollectedData(fixtures, plps);
        }
        else
        {
          flag = false;
          this.ShowMessage("REPORT_FAILED", "ERROR_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
      }
    }
    this.ClearData();
    this.m_plpUsageManager.ClearData();
    return flag;
  }

  public bool CollectData(ITxPlanningObject root)
  {
    this.ClearData();
    bool flag = this.FindFixtures(root);
    if (flag)
      flag = this.FindNotUsedPlps(root);
    return flag;
  }

  public bool ExportCollectedData(List<CApMFExportData> fixtures, List<CApMFExportData> plps)
  {
    bool flag;
    try
    {
      flag = this.m_excelManager.StartExcel();
      if (!flag)
      {
        this.ShowMessage("EXCEL_NOT_INSTALLED", "ERROR_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
      }
      else
      {
        this.m_excelManager.SetExcelVisibility(false);
        flag = this.m_excelManager.ExportData(fixtures, plps);
        if (flag)
        {
          flag = this.m_excelManager.SetExcelVisibility(true);
          if (flag)
          {
            this.m_excelManager.ReleaseExcel();
          }
          else
          {
            this.ShowMessage("EXCEL_NOT_VISIBLE", "ERROR_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            this.m_excelManager.QuitExcel();
          }
        }
        else
          this.m_excelManager.QuitExcel();
      }
    }
    catch (Exception ex)
    {
      this.ShowMessage("REPORT_FAILED", "ERROR_CAPTION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
      this.m_excelManager.QuitExcel();
      flag = false;
    }
    return flag;
  }

  private void ShowMessage(
    string resourceMsg,
    string resourceCaption,
    MessageBoxButtons buttons,
    MessageBoxIcon icons)
  {
    ResourceManager resourceManager = this.GetResourceManager();
    int num = (int) TxMessageBox.Show(resourceManager.GetString(resourceMsg), resourceManager.GetString(resourceCaption), buttons, icons);
  }

  private bool FindFixtures(ITxPlanningObject root)
  {
    bool fixtures = false;
    try
    {
      if (root != null)
      {
        if (root.IsObjectLoaded())
        {
          fixtures = true;
          if (root.EngineeringRepresentation is ITxObjectCollection engineeringRepresentation)
          {
            TxObjectList allDescendants = engineeringRepresentation.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxCompoundResource)));
            if (allDescendants != null)
            {
              if (((Collection<ITxObject>) allDescendants).Count > 0)
              {
                TxObjectList txObjectList = new TxObjectList();
                TxObjectList rootList = new TxObjectList();
                foreach (TxCompoundResource compoundResource in (Collection<ITxObject>) allDescendants)
                {
                  if (TxCompoundResource.op_Inequality(compoundResource, (ITxObject) null) && compoundResource.IsValid())
                  {
                    TxAttribute attribute = compoundResource.GetAttribute("ConfigurationPrototypeId");
                    if (attribute != null && attribute is TxStringAttribute txStringAttribute)
                    {
                      ITxPlanningObject objectFromExternalId = CApMFMappingReportUtils.GetPlanningObjectFromExternalId(txStringAttribute.Value);
                      if (objectFromExternalId != null)
                      {
                        ((Collection<ITxObject>) rootList).Add((ITxObject) objectFromExternalId);
                        ((Collection<ITxObject>) txObjectList).Add((ITxObject) compoundResource);
                      }
                    }
                  }
                }
                if (((Collection<ITxObject>) rootList).Count > 0)
                {
                  if (((Collection<ITxObject>) rootList).Count == ((Collection<ITxObject>) txObjectList).Count)
                  {
                    CApMFMappingReportUtils.CacheData(rootList, "configPrototypes", "Usage", "ConfigurationType");
                    for (int index = 0; index < ((Collection<ITxObject>) rootList).Count; ++index)
                    {
                      ITxPlanningObject planningRepresentation1 = CApMFMappingReportUtils.GetPlanningRepresentation(((Collection<ITxObject>) rootList)[index]);
                      if (planningRepresentation1 != null && planningRepresentation1.FieldWasImported("ConfigurationType") && planningRepresentation1.GetField("ConfigurationType") is string field && field.Equals("Configuration"))
                      {
                        TxCompoundResource compoundResource = ((Collection<ITxObject>) txObjectList)[index] as TxCompoundResource;
                        this.m_fixtures.Add(compoundResource);
                        ITxObject objectForFixture = TxCompoundResourceEx.GetLocatingObjectForFixture(compoundResource);
                        if (objectForFixture != null)
                        {
                          TxMfgFeature txMfgFeature = objectForFixture as TxMfgFeature;
                          if (TxMfgFeature.op_Inequality(txMfgFeature, (ITxObject) null) && txMfgFeature.IsValid())
                          {
                            ITxPlanningObject planningRepresentation2 = txMfgFeature.PlanningRepresentation;
                            if (planningRepresentation2 != null && planningRepresentation2.IsDerivedFromPlanningType("PmPLP"))
                              this.m_usedPlps.Add(txMfgFeature);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    catch (Exception ex)
    {
      this.m_fixtures.Clear();
      fixtures = false;
    }
    return fixtures;
  }

  private bool FindNotUsedPlps(ITxPlanningObject root)
  {
    bool notUsedPlps = false;
    try
    {
      if (root != null)
      {
        if (root.IsObjectLoaded())
        {
          notUsedPlps = true;
          if (root.EngineeringRepresentation is ITxObjectCollection engineeringRepresentation)
          {
            TxObjectList allDescendants = engineeringRepresentation.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxMfgFeature)));
            if (allDescendants != null)
            {
              if (((Collection<ITxObject>) allDescendants).Count > 0)
              {
                foreach (TxMfgFeature txMfgFeature in (Collection<ITxObject>) allDescendants)
                {
                  if (TxMfgFeature.op_Inequality(txMfgFeature, (ITxObject) null) && txMfgFeature.IsValid())
                  {
                    ITxPlanningObject planningRepresentation = txMfgFeature.PlanningRepresentation;
                    if (planningRepresentation != null && planningRepresentation.IsDerivedFromPlanningType("PmPLP") && !this.m_usedPlps.Contains(txMfgFeature))
                      this.m_notUsedPlps.Add(txMfgFeature);
                  }
                }
              }
            }
          }
        }
      }
    }
    catch (Exception ex)
    {
      this.m_notUsedPlps.Clear();
      notUsedPlps = false;
    }
    return notUsedPlps;
  }

  private List<CApMFExportData> PrepareFixturesExportData()
  {
    List<CApMFExportData> capMfExportDataList = new List<CApMFExportData>();
    try
    {
      foreach (TxCompoundResource fixture in this.m_fixtures)
      {
        if (TxCompoundResource.op_Inequality(fixture, (ITxObject) null) && fixture.IsValid())
        {
          CApMFFixtureExportData fixtureExportData = new CApMFFixtureExportData();
          ITxObject objectForFixture = TxCompoundResourceEx.GetLocatingObjectForFixture(fixture);
          if (objectForFixture != null && objectForFixture.IsValid())
          {
            fixtureExportData.PlpFrame = objectForFixture.Name;
            if (objectForFixture is TxFrame)
            {
              string parentName = this.GetParentName(objectForFixture);
              if (parentName != null)
                fixtureExportData.PlpFrame = $"{parentName}\\{fixtureExportData.PlpFrame}";
            }
            if (objectForFixture is ITxLocatableObject itxLocatableObject)
              fixtureExportData.PlpFrameLocation = this.ConvertToExportFormat(itxLocatableObject.AbsoluteLocation);
            if (this.m_canGetPlpUsage)
            {
              ITxPlanningObject planningRepresentation = CApMFMappingReportUtils.GetPlanningRepresentation(objectForFixture);
              if (planningRepresentation != null && planningRepresentation.IsDerivedFromPlanningType("PmPLP"))
              {
                object mappedPlpUsageField = this.m_plpUsageManager.GetMappedPlpUsageField((ITxObject) planningRepresentation, "toolType");
                if (mappedPlpUsageField != null && mappedPlpUsageField is string str)
                  fixtureExportData.PlpUsage = str;
              }
            }
          }
          else if (fixture.GetAttribute("LocatingPoint") is TxTransformationAttribute attribute1)
            fixtureExportData.PlpFrameLocation = this.ConvertToExportFormat(attribute1.Value);
          fixtureExportData.FixtureUnit = fixture.Name;
          fixtureExportData.FixtureUnitLocation = this.ConvertToExportFormat(fixture.AbsoluteLocation);
          if (fixture.Collection != null && ((ITxObject) fixture.Collection).IsValid())
            fixtureExportData.TargetResource = ((ITxObject) fixture.Collection).Name;
          if (fixture.GetAttribute("ValidSolution") is TxIntAttribute attribute2)
            fixtureExportData.ValidSolution = attribute2.Value != 1 ? "-" : "+";
          if (fixture.GetAttribute("ConfigurationPrototypeId") is TxStringAttribute attribute3)
          {
            ITxPlanningObject objectFromExternalId = CApMFMappingReportUtils.GetPlanningObjectFromExternalId(attribute3.Value);
            if (objectFromExternalId != null && objectFromExternalId.FieldWasImported("Usage") && objectFromExternalId.GetField("Usage") is string field)
              fixtureExportData.FixtureUnitUsage = field;
          }
          capMfExportDataList.Add((CApMFExportData) fixtureExportData);
        }
      }
    }
    catch (Exception ex)
    {
      capMfExportDataList.Clear();
    }
    return capMfExportDataList;
  }

  private List<CApMFExportData> PreparePlpsExportData()
  {
    List<CApMFExportData> capMfExportDataList = new List<CApMFExportData>();
    try
    {
      foreach (TxMfgFeature notUsedPlp in this.m_notUsedPlps)
      {
        if (TxMfgFeature.op_Inequality(notUsedPlp, (ITxObject) null) && notUsedPlp.IsValid())
        {
          CApMFPlpExportData capMfPlpExportData = new CApMFPlpExportData();
          capMfPlpExportData.PlpFrame = notUsedPlp.Name;
          capMfPlpExportData.PlpFrameLocation = this.ConvertToExportFormat(notUsedPlp.AbsoluteLocation);
          if (this.m_canGetPlpUsage)
          {
            object mappedPlpUsageField = this.m_plpUsageManager.GetMappedPlpUsageField((ITxObject) notUsedPlp, "toolType");
            if (mappedPlpUsageField != null && mappedPlpUsageField is string str)
              capMfPlpExportData.PlpUsage = str;
          }
          capMfExportDataList.Add((CApMFExportData) capMfPlpExportData);
        }
      }
    }
    catch (Exception ex)
    {
      capMfExportDataList.Clear();
    }
    return capMfExportDataList;
  }

  private ResourceManager GetResourceManager()
  {
    return new ResourceManager("DnProcessSimulateCommands.ModularFixture.MappingReport.Res.ResourceTable", this.GetType().Assembly);
  }

  private string ConvertToExportFormat(TxTransformation location)
  {
    string exportFormat = "";
    if (TxTransformation.op_Inequality(location, (TxTransformation) null))
    {
      CultureInfo provider = new CultureInfo("en-US");
      double num1 = location.RotationRPY_XYZ.X * (180.0 / Math.PI);
      double num2 = location.RotationRPY_XYZ.Y * (180.0 / Math.PI);
      double num3 = location.RotationRPY_XYZ.Z * (180.0 / Math.PI);
      string str1 = exportFormat;
      double num4 = location.Translation.X;
      string str2 = num4.ToString("0.##", (IFormatProvider) provider);
      string str3 = $"{str1}{str2},";
      num4 = location.Translation.Y;
      string str4 = num4.ToString("0.##", (IFormatProvider) provider);
      string str5 = $"{str3}{str4},";
      num4 = location.Translation.Z;
      string str6 = num4.ToString("0.##", (IFormatProvider) provider);
      exportFormat = $"{$"{$"{str5}{str6},"}{num1.ToString("0.##", (IFormatProvider) provider)},"}{num2.ToString("0.##", (IFormatProvider) provider)}," + num3.ToString("0.##", (IFormatProvider) provider);
    }
    return exportFormat;
  }

  private string GetParentName(ITxObject obj)
  {
    string parentName = (string) null;
    if (obj != null)
    {
      try
      {
        ITxObjectCollection collection = obj.Collection;
        switch (collection)
        {
          case null:
          case TxPhysicalRoot _:
            break;
          default:
            parentName = ((ITxObject) collection).Name;
            break;
        }
      }
      catch (Exception ex)
      {
        parentName = (string) null;
      }
    }
    return parentName;
  }
}
